"""
数据库管理工具
提供数据库操作封装
"""

import sqlite3
import logging
from typing import List, Dict, Any, Optional
from config import Config

logger = logging.getLogger(__name__)

class DatabaseManager:
    """数据库管理类"""
    
    def __init__(self, db_path: str = None):
        self.db_path = db_path or Config.DATABASE_PATH
    
    def get_connection(self):
        """获取数据库连接"""
        return sqlite3.connect(self.db_path)
    
    def init_database(self):
        """初始化数据库表"""
        conn = self.get_connection()
        try:
            c = conn.cursor()
            
            # 用户表
            c.execute('''CREATE TABLE IF NOT EXISTS users
                         (id INTEGER PRIMARY KEY AUTOINCREMENT,
                          username TEXT UNIQUE NOT NULL,
                          password TEXT NOT NULL,
                          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
            
            # 简历表
            c.execute('''CREATE TABLE IF NOT EXISTS resumes
                         (id INTEGER PRIMARY KEY AUTOINCREMENT,
                          filename TEXT NOT NULL,
                          name TEXT,
                          phone TEXT,
                          email TEXT,
                          content TEXT,
                          user_id INTEGER,
                          upload_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                          FOREIGN KEY (user_id) REFERENCES users (id))''')
            
            # 分析记录表
            c.execute('''CREATE TABLE IF NOT EXISTS analysis_records
                         (id INTEGER PRIMARY KEY AUTOINCREMENT,
                          resume_id INTEGER,
                          analysis_type TEXT,
                          result TEXT,
                          created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                          FOREIGN KEY (resume_id) REFERENCES resumes (id))''')
            
            conn.commit()
            logger.info("数据库初始化完成")
            
        except Exception as e:
            logger.error(f"数据库初始化失败: {str(e)}")
            raise
        finally:
            conn.close()
    
    def execute_query(self, query: str, params: tuple = ()) -> List[Dict[str, Any]]:
        """执行查询"""
        conn = self.get_connection()
        try:
            c = conn.cursor()
            c.execute(query, params)
            columns = [description[0] for description in c.description]
            results = []
            for row in c.fetchall():
                results.append(dict(zip(columns, row)))
            return results
        finally:
            conn.close()
    
    def execute_update(self, query: str, params: tuple = ()) -> int:
        """执行更新操作"""
        conn = self.get_connection()
        try:
            c = conn.cursor()
            c.execute(query, params)
            conn.commit()
            return c.rowcount
        finally:
            conn.close() 